<!-- 医院管理 -->
<template>
  <PageContainer title="医院管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input v-model="searchForm.keyword" placeholder="请输入医院名称/地址搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="12" class="operate-buttons">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加医院
          </el-button>
          <el-button type="success" @click="handleExport">
            <i class="el-icon-download"></i> 导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 医院表格 -->
    <el-table :data="hospitalList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;">
      <el-table-column label="医院ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="医院名称" prop="name" width="200"></el-table-column>
      <el-table-column label="地址" prop="address" width="300"></el-table-column>
      <el-table-column label="联系电话" prop="phone" width="130" align="center"></el-table-column>
      <el-table-column label="营业时间" prop="businessHours" width="200" align="center"></el-table-column>
      <el-table-column label="医院等级" prop="level" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getLevelTagType(scope.row.level)">
            {{ scope.row.level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleViewDoctor(scope.row)">医生列表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 添加/编辑医院弹窗 -->
    <el-dialog :title="isEdit ? '编辑医院' : '添加医院'" :visible.sync="dialogVisible" width="600px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="医院名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入医院名称"></el-input>
        </el-form-item>
        <el-form-item label="医院等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择医院等级">
            <el-option label="一级医院" value="一级医院"></el-option>
            <el-option label="二级医院" value="二级医院"></el-option>
            <el-option label="三级医院" value="三级医院"></el-option>
            <el-option label="专科医院" value="专科医院"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入医院地址"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="form.businessHours" placeholder="如：08:00-20:00"></el-input>
        </el-form-item>
        <el-form-item label="医院简介" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="5" placeholder="请输入医院简介"></el-input>
        </el-form-item>
        <el-form-item label="医院图片" prop="image">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload" :file-list="fileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用"
            inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getHospitalList, addHospital, editHospital, updateHospitalStatus } from '@/api/hospital'

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 表格数据
const hospitalList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const fileList = ref([])
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'

// 表单数据
const form = reactive({
  id: '',
  name: '',
  level: '',
  phone: '',
  address: '',
  businessHours: '',
  description: '',
  image: '',
  status: 1
})

// 表单校验规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入医院名称', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择医院等级', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入医院地址', trigger: 'blur' }
  ],
  businessHours: [
    { required: true, message: '请输入营业时间', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传医院图片', trigger: 'change' }
  ]
})

// 医院等级标签类型
const getLevelTagType = (level) => {
  const levelTypeMap = {
    '一级医院': 'info',
    '二级医院': 'success',
    '三级医院': 'primary',
    '专科医院': 'warning'
  }
  return levelTypeMap[level] || 'default'
}

// 获取医院列表
const fetchHospitalList = async () => {
  try {
    loading.value = true
    const res = await getHospitalList({
      keyword: searchForm.keyword,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    hospitalList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取医院列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchHospitalList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchHospitalList()
}

// 添加医院
const handleAdd = () => {
  isEdit.value = false
  // 重置表单
  form.id = ''
  form.name = ''
  form.level = ''
  form.phone = ''
  form.address = ''
  form.businessHours = ''
  form.description = ''
  form.image = ''
  form.status = 1
  fileList.value = []
  dialogVisible.value = true
}

// 编辑医院
const handleEdit = (row) => {
  isEdit.value = true
  // 填充表单
  form.id = row.id
  form.name = row.name
  form.level = row.level
  form.phone = row.phone
  form.address = row.address
  form.businessHours = row.businessHours
  form.description = row.description
  form.image = row.image
  form.status = row.status
  // 图片列表
  fileList.value = row.image ? [{ url: row.image }] : []
  dialogVisible.value = true
}

// 查看医院医生列表
const handleViewDoctor = (row) => {
  // 跳转到医生管理页面并筛选该医院的医生
  console.log('查看医院医生:', row.id, row.name)
  // 实际项目中可以通过路由参数传递医院ID
  // router.push({ path: '/super-admin/doctor-manage', query: { hospitalId: row.id } })
  ElMessage.info(`查看${row.name}的医生列表`)
}

// 改变医院状态
const handleStatusChange = async (row) => {
  try {
    await updateHospitalStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success(`医院已${row.status === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    // 失败时回滚状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑医院
      await editHospital(form)
      ElMessage.success('编辑医院成功')
    } else {
      // 添加医院
      await addHospital(form)
      ElMessage.success('添加医院成功')
    }
    dialogVisible.value = false
    fetchHospitalList()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑医院失败' : '添加医院失败')
  }
}

// 上传图片成功
const handleUploadSuccess = (response) => {
  form.image = response.data.url
  fileList.value = [{ url: response.data.url }]
}

// 上传图片前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value?.resetFields()
  fileList.value = []
  dialogVisible.value = false
}

// 导出数据
const handleExport = () => {
  // 实际项目中实现导出逻辑
  ElMessage.success('导出成功')
}

// 页面挂载时获取数据
onMounted(() => {
  fetchHospitalList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .search-input {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>